//
//  SpecialAudioCell.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/12/29.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "SpecialAudioCell.h"

@interface SpecialAudioCell ()

@property (weak, nonatomic) IBOutlet UILabel *specailAudioNameLabel;

@property (weak, nonatomic) IBOutlet UIButton *downloadBtn;

@property (weak, nonatomic) IBOutlet UILabel *dateLabel;

@property (weak, nonatomic) IBOutlet UILabel *timeLabel;

@property (weak, nonatomic) IBOutlet UILabel *listenCountLabel;

@end

@implementation SpecialAudioCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    self.selectionStyle =  UITableViewCellSelectionStyleNone;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setDownloadProgress:) name:MCDownloadStartNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setDownloadProgress:) name:MCDownloadStopNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setDownloadProgress:) name:MCDownloadFinishNotification object:nil];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setPoint:(ScenicPoint *)point {
    
    _point = point;
    
    self.specailAudioNameLabel.text = point.spotname;
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:point.createtime / 1000];
    
    if (date.isToday) {
        
        self.dateLabel.text = MYLocalizedString(@"COMMENT_TODAY", nil);
    } else {
        
        if (date.year == [NSDate date].year) {
            self.dateLabel.text = [date stringWithFormat:@"MM-dd"];
        } else {
            
            self.dateLabel.text = [date stringWithFormat:@"yyyy-MM-dd"];
        }
    }
    
    NSString *duration = [NSString stringWithFormat:@"%@:%@",MYLocalizedString(@"COMMENT_DURATION", nil),[self secondToString:(point.duration / 1000)]];
    
    self.timeLabel.text = duration;
    
    self.listenCountLabel.text = [NSString stringWithFormat:@"%@:%@",MYLocalizedString(@"COMMENT_LISETEN_TIMES", nil),point.times];

    [self setDownloadProgress:nil];
    
}

- (NSString *)secondToString:(NSInteger)duration {
    
    NSInteger seconds = duration % 60;
    NSInteger minutes = (duration / 60);
    return [NSString stringWithFormat:@"%02d:%02d", (int)minutes, (int)seconds];
}

- (IBAction)downloadBtnClicketed:(id)sender {
    
    if (![IGUtil hasLoginOrPresentLogin]) {
        
        [self.superVC.sl_popupController dismiss];
        return;
    }
    
    MCDownloadReceipt *receipt = [[DownloadManager sharedManager] downloadReceiptForURLString:self.point.playpath];
    
    if (receipt.state == MCDownloadStateCompleted) {
        return;
    }
    
    [[DownloadManager sharedManager] addDownloadWithLineModel:self.model point:self.point];
}

- (void)setDownloadProgress:(NSNotification *)notification {
    
    if (notification && ![notification.object isKindOfClass:NSClassFromString(@"MCDownloadOperation")]) {
        return;
    }
    
    
    MCDownloadReceipt *receipt1 = [notification.object valueForKey:@"receipt"];
    
    if (receipt1 && [receipt1 isKindOfClass:[MCDownloadReceipt class]] && ![receipt1.url isEqualToString:self.point.playpath]) {
        
        return;
    }
    
    MCDownloadReceipt *receipt = [[DownloadManager sharedManager] downloadReceiptForURLString:self.point.playpath];
    
    __block NSString *downloadText = nil;
    
    if (receipt.state == MCDownloadStateDownloading) {
        
        downloadText = [NSString localizedStringWithFormat:MYLocalizedString(@"MYDOWNLOAD_STATE_DOWNLOADING", nil),receipt.progress.fractionCompleted * 100];
        
    } else if (receipt.state == MCDownloadStateCompleted) {
        
        downloadText = MYLocalizedString(@"MYDOWNLOAD_STATE_SUCCESS", nil);
        
    } else if (receipt.state == MCDownloadStateFailed) {
        
        downloadText = MYLocalizedString(@"MYDOWNLOAD_STATE_FAILED", nil);
        
    } else if (receipt.state == MCDownloadStateSuspened) {
        
        downloadText = MYLocalizedString(@"MYDOWNLOAD_STATE_SUSPEND", nil);
        
    }
    
    if (!downloadText) {
        
        [self.downloadBtn setImage:[UIImage imageNamed:@"audioDownload"] forState:UIControlStateNormal];
        [self.downloadBtn setTitle:nil forState:UIControlStateNormal];
        
        return;
    }
    
    [self.downloadBtn setImage:nil forState:UIControlStateNormal];
    [self.downloadBtn setTitle:downloadText forState:UIControlStateNormal];
    
    @weakify(self);
    receipt.downloaderProgressBlock = ^(NSInteger receivedSize, NSInteger expectedSize, NSInteger speed, NSURL * _Nullable targetURL) {
        @strongify(self);
        
        if (![targetURL.absoluteString isEqualToString:self.point.playpath]) {
            
            return;
        }
        
        CGFloat progress = receivedSize * 1.0f / expectedSize;
        
        if (progress == 1) {
            downloadText = MYLocalizedString(@"MYDOWNLOAD_STATE_SUCCESS", nil);
        }
        
        if (progress >= 1) {
            progress = 1;
        } else if (progress < 0) {
            progress = 0;
        }
        
        downloadText = [NSString localizedStringWithFormat:MYLocalizedString(@"MYDOWNLOAD_STATE_DOWNLOADING", nil),progress * 100];
        
        [self.downloadBtn setImage:nil forState:UIControlStateNormal];
        [self.downloadBtn setTitle:downloadText forState:UIControlStateNormal];
    };
    
    receipt.downloaderCompletedBlock = ^(MCDownloadReceipt *receipt, NSError * _Nullable error, BOOL finished) {
        
        if (![receipt.url isEqualToString:self.point.playpath]) {
            
            return;
        }
        
        if (error) {
            downloadText = MYLocalizedString(@"MYDOWNLOAD_STATE_FAILED", nil);
            IGLog(@"总进度------ cell 下载失败 %@",self.point.spotname);
            
        } else {
            
            downloadText = MYLocalizedString(@"MYDOWNLOAD_STATE_SUCCESS", nil);
            IGLog(@"总进度------ cell 已下载 %@",self.point.spotname);
        }
        [self.downloadBtn setImage:nil forState:UIControlStateNormal];
        [self.downloadBtn setTitle:downloadText forState:UIControlStateNormal];
    };
    
}

@end
